<template>
  <el-upload
    class="avatar-uploader"
    :class="[sizeClass]"
    :action="uploadUrl"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :on-error="handleAvatarError"
    :before-upload="beforeAvatarUpload">
    <img v-if="value" :src="$imgUrl(value)" class="avatar">
    <i v-else
       :class="[sizeClass]"
       class="el-icon-plus
     avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import ResponseCode from '@/constants/ResponseCode'
import System from '@/constants/System'
export default {
  name: 'CAvatarUpload',
  data () {
    return {
      uploadUrl: System.UPLOAD_URL
    }
  },
  props: {
    size: {
      type: String,
      default: 'middle'
    },
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    sizeClass () {
      return `avatar--${this.size}`
    }
  },
  methods: {
    handleAvatarSuccess (res) {
      if (res.code === ResponseCode.SUCCESS) {
        this.setCurrentValue(res.data[0].imgUrl)
      } else {
        this.$message.error(res.msg)
      }
    },
    setCurrentValue (value) {
      this.$emit('input', value)
    },
    handleAvatarError () {
      this.$message.error('网络异常')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  width: 100%;
  height: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
</style>

<style scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.avatar--small {
  width: 128px;
  height: 128px;
  line-height: 128px;
}

.avatar--middle {
  width: 178px;
  height: 178px;
  line-height: 178px;
}
</style>
